<template>
  <div>
    <el-upload
      list-type="picture-card"
      :file-list="fileList"
      action="#"
      :on-preview="onPreview"
      :on-remove="onRemove"
      :on-change="onChange"
      :class="{active:fileList.length>0}"
      :http-request="uploadFn"
      :before-upload="beforeUpload"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress v-if="showProgress" class="progress" :text-inside="true" :stroke-width="18" :percentage="percentage" status="success" />
    <el-dialog title="预览图片" :visible="showDialog" @close="showDialog=false ">
      <img class="previewImg" :src="imgUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
// 引入
import COS from 'cos-js-sdk-v5'
// 实例化
const cos = new COS({
  SecretId: 'AKIDe7KHxMddMozuYv1rQijTw83h5CQP8alf',
  SecretKey: 'e29zYqrb4GBpCI8hz0kDPKzNTIq77qIT'
})
export default {
  data() {
    return {
      fileList: [],
      imgUrl: '',
      showDialog: false,
      percentage: 0,
      showProgress: false
    }
  },
  methods: {
    onPreview(file) {
      this.showDialog = true
      this.imgUrl = file.url
    },
    onRemove(file, newFileList) {
      this.fileList = newFileList
    },
    onChange(file, newFileList) {
      this.fileList = newFileList
      // console.log(52, newFileList)
    },
    beforeUpload(file) {
      this.showProgress = true
      if (file.size > 2 * 1024 * 1024) {
        this.$message.warning('文件大小不能超过2M')
        return false
      }
      const whiteList = ['image/jpeg', 'image/png']
      if (!whiteList.includes(file.type)) {
        this.$message.warning('图片文件格式错误,只支持JPEG和PNG')
        return false
      }
    },
    uploadFn(params) {
      cos.putObject({
        Bucket: 'hy-1307304499', /* 必须 */
        Region: 'ap-nanjing', /* 存储桶所在地域，必须字段 */
        Key: params.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          // //console.log(JSON.stringify(progressData))
          this.percentage = progressData.percent * 100
        }
      }, (err, data) => {
        // console.log(err || data)
        if (!err) {
          this.fileList[0].url = 'http://' + data.Location
          this.fileList[0].status = 'success'
        }
        setTimeout(() => {
          this.showProgress = false
        }, 1000)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.active{
  ::v-deep.el-upload--picture-card{
    display: none;
  }
}
::v-deep.previewImg{
  width: 100%;
}
.progress{
  width: 146px;
}
</style>
